<template>
  <div class="device-form-container">
    <el-page-header @back="goBack" :title="isEdit ? '编辑设备' : '添加设备'" />
    
    <el-card class="form-card" shadow="never">
      <el-form 
        ref="deviceFormRef" 
        :model="deviceForm" 
        :rules="rules" 
        label-width="120px" 
        label-position="right"
        status-icon
      >
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称" maxlength="50" />
        </el-form-item>
        
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="deviceForm.deviceCode" placeholder="请输入设备编号" maxlength="30" />
        </el-form-item>
        
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="deviceForm.type" placeholder="请选择设备类型" style="width: 100%">
            <el-option label="LCD屏幕" value="LCD_SCREEN" />
            <el-option label="LED显示屏" value="LED_DISPLAY" />
            <el-option label="数字标牌" value="DIGITAL_SIGNAGE" />
            <el-option label="触摸屏" value="TOUCH_SCREEN" />
            <el-option label="信息亭" value="INTERACTIVE_KIOSK" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备位置" prop="location">
          <el-input 
            v-model="deviceForm.location" 
            placeholder="请输入设备位置" 
            maxlength="100" 
            @input="updateAddressInput"
          />
          
          <!-- 新增地图位置选择器 -->
          <div class="map-container">
            <el-divider>在地图上选择位置</el-divider>
            
            <!-- 地图搜索框 -->
            <div class="map-search">
              <el-input
                v-model="searchAddress"
                placeholder="搜索地址"
                clearable
                @keyup.enter="searchMapLocation"
              >
                <template #append>
                  <el-button @click="searchMapLocation" :loading="searchLoading">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <!-- 地图显示区域 -->
            <div id="map-container" class="map-viewer"></div>
            
            <!-- 经纬度信息显示 -->
            <div class="location-info" v-if="locationData.lng && locationData.lat">
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="经度">{{ locationData.lng.toFixed(6) }}</el-descriptions-item>
                <el-descriptions-item label="纬度">{{ locationData.lat.toFixed(6) }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="设备规格" prop="specifications">
          <el-input 
            v-model="deviceForm.specifications" 
            placeholder="请输入设备规格，例如：屏幕尺寸、分辨率等" 
            type="textarea" 
            :rows="4" 
            maxlength="500" 
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getDeviceDetail, createDevice, updateDevice } from '@/api/device';
import AMapLoader from '@amap/amap-jsapi-loader';

const route = useRoute();
const router = useRouter();
const deviceId = computed(() => route.params.id);
const isEdit = computed(() => !!deviceId.value);
const loading = ref(false);
const deviceFormRef = ref(null);

// 地图相关状态
const searchAddress = ref('');
const searchLoading = ref(false);
let mapInstance = null;
let marker = null;
let geocoder = null;

// 位置数据
const locationData = reactive({
  lng: null,
  lat: null,
  address: ''
});

// 表单数据
const deviceForm = reactive({
  name: '',
  deviceCode: '',
  type: '',
  location: '',
  specifications: '',
  latitude: null,
  longitude: null
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度应为2-50个字符', trigger: 'blur' }
  ],
  deviceCode: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
    { min: 2, max: 30, message: '长度应为2-30个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  location: [
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  specifications: [
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ]
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 初始化地图
const initMap = async () => {
  try {
    console.log('开始加载地图...');
    const AMap = await AMapLoader.load({
      key: '2bd1031aa08256eeba5539a5577c3ff7',// 确保替换为真实的API密钥
      version: '2.0',
      plugins: ['AMap.Geocoder', 'AMap.PlaceSearch']
    });
    
    console.log('地图SDK加载成功');
    
    // 初始中心位置（默认北京）
    const defaultCenter = [116.397428, 39.90923];
    let center = defaultCenter;
    
    // 如果编辑模式且有坐标，使用设备坐标
    if (isEdit.value && deviceForm.longitude && deviceForm.latitude) {
      center = [deviceForm.longitude, deviceForm.latitude];
      locationData.lng = deviceForm.longitude;
      locationData.lat = deviceForm.latitude;
      locationData.address = deviceForm.location;
    }
    
    // 创建地图实例
    mapInstance = new AMap.Map('map-container', {
      zoom: 13,
      center: center
    });
    
    // 创建地理编码器
    geocoder = new AMap.Geocoder({
      city: '全国'
    });
    
    // 如果有初始位置，创建标记
    if (isEdit.value && deviceForm.longitude && deviceForm.latitude) {
      createMarker([deviceForm.longitude, deviceForm.latitude]);
    }
    
    // 添加地图点击事件
    mapInstance.on('click', (e) => {
      const lnglat = e.lnglat;
      createMarker([lnglat.getLng(), lnglat.getLat()]);
      reverseGeocode(lnglat);
    });
    
    console.log('地图初始化完成');
  } catch (error) {
    console.error('地图初始化失败:', error);
    ElMessage.error('地图加载失败，请检查API密钥设置');
  }
};

// 创建标记
const createMarker = (position) => {
  if (marker) {
    mapInstance.remove(marker);
  }
  
  marker = new AMap.Marker({
    position,
    draggable: true,
    cursor: 'move',
    animation: 'AMAP_ANIMATION_DROP'
  });
  
  mapInstance.add(marker);
  mapInstance.setCenter(position);
  
  // 拖拽结束后更新位置
  marker.on('dragend', (e) => {
    const lnglat = e.target.getPosition();
    reverseGeocode(lnglat);
  });
  
  // 更新位置数据
  locationData.lng = position[0];
  locationData.lat = position[1];
  
  // 同步到表单
  deviceForm.longitude = position[0];
  deviceForm.latitude = position[1];
};

// 地址搜索
const searchMapLocation = async () => {
  if (!searchAddress.value.trim()) {
    ElMessage.warning('请输入搜索地址');
    return;
  }
  
  if (!geocoder) {
    ElMessage.error('地图尚未完全加载，请稍后再试');
    return;
  }
  
  searchLoading.value = true;
  try {
    geocoder.getLocation(searchAddress.value, (status, result) => {
      searchLoading.value = false;
      
      if (status === 'complete' && result.geocodes.length) {
        const location = result.geocodes[0].location;
        createMarker([location.getLng(), location.getLat()]);
        
        // 更新地址
        locationData.address = result.geocodes[0].formattedAddress;
        deviceForm.location = locationData.address;
      } else {
        ElMessage.warning('未找到该地址');
      }
    });
  } catch (error) {
    searchLoading.value = false;
    console.error('地址搜索失败:', error);
    ElMessage.error('地址搜索失败');
  }
};

// 根据经纬度获取地址
const reverseGeocode = (lnglat) => {
  if (!geocoder) return;
  
  geocoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      const addressInfo = result.regeocode.formattedAddress;
      locationData.address = addressInfo;
      deviceForm.location = addressInfo;
    } else {
      console.error('逆地理编码失败');
    }
  });
};

// 当用户手动输入地址时，更新搜索框
const updateAddressInput = () => {
  searchAddress.value = deviceForm.location;
};

// 获取设备详情（编辑模式）
const fetchDeviceDetail = async () => {
  if (!isEdit.value) return;
  
  loading.value = true;
  try {
    const { data } = await getDeviceDetail(deviceId.value);
    
    if (data.code === 200) {
      const device = data.data;
      deviceForm.name = device.name;
      deviceForm.deviceCode = device.deviceCode;
      deviceForm.type = device.type;
      deviceForm.location = device.location;
      deviceForm.specifications = device.specifications;
      deviceForm.latitude = device.latitude;
      deviceForm.longitude = device.longitude;
      
      // 同步到搜索框
      searchAddress.value = device.location;
    } else {
      ElMessage.error(data.message || '获取设备详情失败');
      goBack();
    }
  } catch (error) {
    console.error('获取设备详情失败:', error);
    ElMessage.error('获取设备详情失败');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!deviceFormRef.value) return;
  
  await deviceFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单信息');
      return;
    }
    
    loading.value = true;
    try {
      // 构建提交数据
      const submitData = {
        ...deviceForm
      };
      
      let response;
      if (isEdit.value) {
        response = await updateDevice(deviceId.value, submitData);
      } else {
        response = await createDevice(submitData);
      }
      
      const { data } = response;
      
      if (data.code === 200) {
        ElMessage.success(isEdit.value ? '更新设备成功' : '添加设备成功');
        router.push('/device-owner/devices');
      } else {
        ElMessage.error(data.message || (isEdit.value ? '更新设备失败' : '添加设备失败'));
      }
    } catch (error) {
      console.error(isEdit.value ? '更新设备失败:' : '添加设备失败:', error);
      ElMessage.error(isEdit.value ? '更新设备失败' : '添加设备失败');
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (deviceFormRef.value) {
    deviceFormRef.value.resetFields();
  }
  
  // 重置地图和位置数据
  locationData.lng = null;
  locationData.lat = null;
  locationData.address = '';
  searchAddress.value = '';
  
  // 重置标记
  if (marker && mapInstance) {
    mapInstance.remove(marker);
    marker = null;
  }
  
  // 重置地图视图
  if (mapInstance) {
    mapInstance.setCenter([116.397428, 39.90923]);
    mapInstance.setZoom(13);
  }
};

onMounted(() => {
  if (isEdit.value) {
    fetchDeviceDetail();
  }
  
  // 初始化地图
  nextTick(() => {
    initMap();
  });
});

onUnmounted(() => {
  // 销毁地图实例
  if (mapInstance) {
    mapInstance.destroy();
    mapInstance = null;
  }
});
</script>

<style scoped>
.device-form-container {
  padding: 20px;
}

.form-card {
  margin-top: 20px;
  max-width: 800px;
}

.map-container {
  margin-top: 15px;
}

.map-search {
  margin-bottom: 10px;
}

.map-viewer {
  width: 100%;
  height: 400px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}

.location-info {
  margin-top: 10px;
}

.el-descriptions {
  margin-top: 10px;
}
</style>